package com.david.controller.api;

import com.david.entity.AdminInfo;
import com.david.model.api.LoginRequest;
import com.david.model.api.Response;
import com.david.service.AdminInfoService;
import com.david.utils.IPUtils;
import com.david.annotation.IgnoreSecurity;
import com.david.utils.WebAuthentication;
import com.google.common.collect.ImmutableMap;
import com.mysql.jdbc.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    AdminInfoService adminInfoService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //此注解可以不用登陆
    @IgnoreSecurity
    @PostMapping("/login")
    @ApiOperation(value = "登陆", notes = "账号密码登陆", tags = "login")
    public Response<Map> Login(HttpServletRequest httprequest, @RequestBody LoginRequest request) throws Exception {
        Response<Map> result = new Response<>();

        if (StringUtils.isNullOrEmpty(request.getUserName()) || StringUtils.isNullOrEmpty(request.getPassword())) {
            result.data = ImmutableMap.of("result", false, "errMsg", "账号或密码不能为空!");
            return result;
        }
        AdminInfo info = new AdminInfo();
        info.setUserName(request.getUserName());
        info.setPassWord(WebAuthentication.encryptionData(request.getPassword()));

        AdminInfo loginResult = adminInfoService.checkLogin(info);

        if (loginResult == null) {
            result.data = ImmutableMap.of("result", false, "errMsg", "账号或密码不正确!");
            return result;
        }

        if (!loginResult.isEnable) {
            result.data = ImmutableMap.of("result", false, "errMsg", "该账号已禁止登陆!");
            return result;
        }

        logger.info(String.format("管理员登陆了 ， 登陆ID：%s ; 登陆IP： %s", String.valueOf(loginResult.id), IPUtils.getIpAddr(httprequest)));
        WebAuthentication.SignIn(request.getUserName(), loginResult.id);

        result.data = ImmutableMap.of("result", true, "token", loginResult.id);

        return result;
    }

    /**
     * 退出登陆
     * @return
     * @throws Exception
     */
    @GetMapping("/logout")
    public Response<Map> logout() throws Exception {
        Response<Map> result = new Response<Map>();
        WebAuthentication.signOut();
        result.data = ImmutableMap.of("result", true);
        return result;
    }

}
